package com.vb.webpress.data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.vb.webpress.data.Constants.AccountColum;
import com.vb.webpress.data.Constants.NewsColum;

public class AccountDAO {
	
	public static boolean addAccount(Account account){
		Connection conn = null;
		PreparedStatement pstm = null;
		try {
			conn = DbManager.getConnection();
			pstm = conn.prepareStatement(AccountColum.Account_TABLE_ADD_ACCOUNT);
			pstm.setString(1, account.getName());
			pstm.setString(2, account.getPassword());
			pstm.setString(3, account.getRole());
			return pstm.execute();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try{
				if(pstm != null)
					pstm.close();
				if(conn != null)
					conn.close();
			}catch(Exception e){
				e.printStackTrace();
			}
			
		}
		return false;
	}
	public static boolean validateAccount(String idOrName, String password){

		Connection conn = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			conn = DbManager.getConnection();
			pstm = conn.prepareStatement(AccountColum.Account_TABLE_FIND_ACCOUNT);
			int i = -1;
			try{
				i = Integer.valueOf(idOrName);
			}catch(Exception e){
				
			}
			pstm.setInt(1, i);
			pstm.setString(2, idOrName);
			rs = pstm.executeQuery();
			if(rs.next())
				return password.equals(rs.getString(Constants.AccountColum.PASSWORD));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try{
				if(pstm != null)
					pstm.close();
				if(conn != null)
					conn.close();
			}catch(Exception e){
				e.printStackTrace();
			}
			
		}
		return false;
	}
	public static boolean updatePassword(String idOrName, String newPassword){
		Connection conn = null;
		PreparedStatement pstm = null;
		try {
			conn = DbManager.getConnection();
			pstm = conn.prepareStatement(AccountColum.Account_TABLE_UPDATE_PASSWORD);
			pstm.setString(1, newPassword);
			int i = -1;
			try{
				i = Integer.valueOf(idOrName);
			}catch(Exception e){
				
			}
			pstm.setInt(2, i);
			pstm.setString(3, idOrName);
			return pstm.execute();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try{
				if(pstm != null)
					pstm.close();
				if(conn != null)
					conn.close();
			}catch(Exception e){
				e.printStackTrace();
			}
			
		}
		return false;
	}
}
